import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus'

// 从环境变量获取高德地图 API Key
const API_KEY = import.meta.env.VITE_AMAP_KEY
const SECURITY_KEY = import.meta.env.VITE_AMAP_SECURITY_KEY

let mapInstance: any = null
let geocoder: any = null

// 设置安全密钥
window._AMapSecurityConfig = {
    securityJsCode: SECURITY_KEY
}

export const initAMap = async () => {
    if (mapInstance) return mapInstance

    try {
        const AMap = await AMapLoader.load({
            key: API_KEY,
            version: '2.0',
            plugins: ['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch']
        })

        mapInstance = new AMap.Map('map-container', {
            zoom: 11,
            center: [116.397428, 39.90923]
        })

        geocoder = new AMap.Geocoder({
            city: '全国'
        })

        return mapInstance
    } catch (error) {
        console.error('高德地图初始化失败:', error)
        throw error
    }
}

export const geocode = async (address: string) => {
    if (!geocoder) {
        await initAMap()
    }

    return new Promise((resolve, reject) => {
        geocoder.getLocation(address, (status: string, result: any) => {
            if (status === 'complete' && result.info === 'OK') {
                resolve(result.geocodes[0])
            } else {
                reject(new Error('地理编码失败'))
            }
        })
    })
}

export const reverseGeocode = async (location: [number, number]) => {
    if (!geocoder) {
        await initAMap()
    }

    return new Promise((resolve, reject) => {
        geocoder.getAddress(location, (status: string, result: any) => {
            if (status === 'complete' && result.info === 'OK') {
                resolve(result.regeocode)
            } else {
                reject(new Error('逆地理编码失败'))
            }
        })
    })
}

export const searchPlace = async (keyword: string, city = '全国') => {
    if (!mapInstance) {
        await initAMap()
    }

    const placeSearch = new (window as any).AMap.PlaceSearch({
        city,
        pageSize: 10,
        pageIndex: 1
    })

    return new Promise((resolve, reject) => {
        placeSearch.search(keyword, (status: string, result: any) => {
            if (status === 'complete' && result.info === 'OK') {
                resolve(result.poiList.pois)
            } else {
                reject(new Error('地点搜索失败'))
            }
        })
    })
}

export const calculateDistance = async (from: [number, number], to: [number, number]) => {
    if (!mapInstance) {
        await initAMap()
    }

    return new Promise((resolve, reject) => {
        const driving = new (window as any).AMap.Driving({
            policy: (window as any).AMap.DrivingPolicy.LEAST_TIME
        })

        driving.search(
            new (window as any).AMap.LngLat(from[0], from[1]),
            new (window as any).AMap.LngLat(to[0], to[1]),
            (status: string, result: any) => {
                if (status === 'complete' && result.info === 'OK') {
                    const route = result.routes[0]
                    resolve({
                        distance: route.distance,
                        duration: route.time,
                        path: route.path
                    })
                } else {
                    reject(new Error('距离计算失败'))
                }
            }
        )
    })
}

export const createLocationPicker = (map: AMap.Map) => {
    const marker = new AMap.Marker({
        draggable: true
    })

    map.add(marker)

    // 监听地图点击事件
    map.on('click', (e: any) => {
        const position = [e.lnglat.lng, e.lnglat.lat]
        marker.setPosition(position)
        updateAddress(position)
    })

    // 监听标记拖动事件
    marker.on('dragend', (e: any) => {
        const position = [e.lnglat.lng, e.lnglat.lat]
        updateAddress(position)
    })

    // 更新地址信息
    const updateAddress = (position: [number, number]) => {
        geocoder.getAddress(position, (status: string, result: any) => {
            if (status === 'complete' && result.regeocode) {
                const address = result.regeocode.formattedAddress
                marker.setTitle(address)
                marker.emit('address', { position, address })
            } else {
                ElMessage.error('获取地址信息失败')
            }
        })
    }

    return marker
}

export const getCurrentPosition = () => {
    return new Promise((resolve, reject) => {
        if (!navigator.geolocation) {
            reject(new Error('浏览器不支持定位功能'))
            return
        }

        navigator.geolocation.getCurrentPosition(
            (position) => {
                resolve([position.coords.longitude, position.coords.latitude])
            },
            (error) => {
                reject(error)
            },
            {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            }
        )
    })
}

export default {
    initAMap,
    geocode,
    reverseGeocode,
    searchPlace,
    calculateDistance,
    createLocationPicker,
    getCurrentPosition
} 